import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/app.dart';
import 'package:flutter_rider/main/page/debug_page.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/module/login/models/user_model.dart';
import 'package:flutter_rider/module/login/provider/user_provider.dart';
import 'package:flutter_rider/module/mine/provider/mine_provider.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import '../../../config.dart';
import '../../../main/page/main_page.dart';

class LoginPage extends ConsumerStatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends ConsumerState<LoginPage> {
  var _index = 0;
  final _phoneTextController = TextEditingController();
  final _pwdTextController = TextEditingController();
  final _codeTextController = TextEditingController();
  Timer? _timer;
  var _seconds = 0;

  var _clickCount = 0;
  Timer? _clickTimer;
  final _scrollController = ScrollController();
  var _isShowKeyboard = false;

  @override
  void initState() {
    super.initState();

    if (Api.getAccount().isNotEmpty){
        _phoneTextController.text = Api.getAccount();
    }

    if (kDebugMode) {
      _codeTextController.text = "123456";
    }
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _clickTimer?.cancel();
    _phoneTextController.dispose();
    _pwdTextController.dispose();
    _codeTextController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (MediaQuery.of(context).viewInsets.bottom > 0) {
      if (!_isShowKeyboard) {
        _isShowKeyboard = true;
        //横屏, 因为高度不够, 就不用滚到底部了
        if (!App.isLandscape) {
          Future.delayed(const Duration(microseconds: 10), () {
            _scrollController
                .jumpTo(_scrollController.position.maxScrollExtent);
          });
        }
      }
    } else {
      _isShowKeyboard = false;
    }
    return Scaffold(
      backgroundColor: UIColor.color_content,
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        controller: _scrollController,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: double.infinity,
              height: 240.rpx,
              alignment: Alignment.center,
              child: GestureDetector(
                  onTap: () async {
                    _clickCount += 1;
                    if (_clickCount >= 5 &&
                        _phoneTextController.text == "888888") {
                      Tip.show("debug模式开启");
                      _clickCount = 0;
                      var sp = await SharedPreferences.getInstance();
                      sp.setBool("debug_mode", true);
                      App.isDebugMode = true;
                      setState(() {});
                    }
                    _clickTimer ??= Timer(const Duration(seconds: 5), () {
                      _clickCount = 0;
                      _clickTimer = null;
                    });
                  },
                  child: Column(
                    children: [
                      60.hspace,
                      SvgPicture.asset(R.image_logo2,
                          width: 80.rpx, height: 80.rpx),
                      Container(
                        margin: EdgeInsets.only(right: 12.rpx),
                        alignment: Alignment.bottomRight,
                        child: App.isDebugMode
                            ? UText.get("debug", Colors.red, 20.rpx).onTap(() {
                                OpenUtils.open(context, DebugPage());
                              })
                            : 0.wspace,
                      ),
                    ],
                  )),
              decoration: const BoxDecoration(
                color: Colors.white,
                image: DecorationImage(
                  image: AssetImage(R.image_poi_login_bg),
                  fit: BoxFit.fill, // 完全填充
                ),
              ),
            ),
            Container(
                padding: EdgeInsets.only(left: 24.rpx, right: 24.rpx),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _renderTab(),
                      10.hspace,
                      ..._renderPwdLogin(),
                      30.hspace,
                      _renderButton(),
                      20.hspace,
                      //_renderSlider(),
                      SizedBox(
                          height: MediaQuery.of(context).viewInsets.bottom),
                    ]))
          ],
        ),
      ),
    );
  }

  _renderButton() {
    var isEnable = _phoneTextController.text.length == 11 &&
        (_pwdTextController.text.length >= 6 ||
            _codeTextController.text.length >= 6);
    return MaterialButton(
      minWidth: double.infinity,
      height: 40.rpx,
      onPressed: isEnable
          ? () {
              _onClickLogin();
            }
          : null,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(4.rpx),
      ),
      color: UIColor.color_primary,
      disabledColor: Colors.black.withOpacity(0.26),
      child: UText.get("登录", Colors.white, 14.rpx),
    );
  }

  List<Widget> _renderPwdLogin() {
    return [
      _renderPhone(),
      _index == 0 ? _renderPwd() : _renderCode(),
    ];
  }

  _onClickLogin() {
    var tel = _phoneTextController.text;
    var pwd = _pwdTextController.text;
    var code = _codeTextController.text;
    if (tel.isEmpty) {
      Tip.show("手机号不能为空");
      return;
    }
    if (_index == 0) {
      if (pwd.isEmpty) {
        Tip.show("验证码不能为空");
        return;
      }
    } else {
      if (code.isEmpty) {
        Tip.show("验证码不能为空");
        return;
      }
    }
    var json = {};
    json["mobile"] = tel;
    json["mode"] = _index == 0 ? "password" : "sms_code";
    if (_index == 0) {
      json["password"] = pwd;
    } else {
      json["sms_code"] = code;
    }
    var url = "/user/login";
    Api.submitx(context, url, data: json, failTip: "登录失败", success: (data) {
      // context.read<UserModelProvider>()
      //     .setUserModel(UserModel.fromMap(data));
      ref
          .read(userModelProvider.notifier)
          .setUserModel(UserModel.fromMap(data));
      Api.saveLoginInfo(data);
      ref.read(isWorkProvider.notifier).getWork();
      Navigator.pushAndRemoveUntil(context,
          MaterialPageRoute(builder: (context) {
        return MainPage();
      }), (route) => false);
    });
  }

  Widget _renderPhone() {
    return TextField(
      style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
      controller: _phoneTextController,
      cursorColor: UIColor.color_primary,
      cursorHeight: 20.rpx,
      keyboardType: TextInputType.phone,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp("[0-9]")),
      ],
      maxLength: 11,
      decoration: InputDecoration(
        counterText: "",
        prefixIconConstraints:
            BoxConstraints(minWidth: 32.rpx, minHeight: 24.rpx),
        prefixIcon:
            SvgPicture.asset(R.image_login_user, width: 24.rpx, height: 24.rpx),
        border: UnderlineInputBorder(
          borderSide: BorderSide(color: UIColor.color_divider, width: 1.rpx),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: UIColor.color_primary, width: 1.rpx),
        ),
        hintText: "请输入手机号",
        hintStyle:
            TextStyle(color: Colors.black.withOpacity(0.26), fontSize: 16.rpx),
        suffixIcon: _phoneTextController.text.isNotEmpty
            ? IconButton(
                iconSize: 20.rpx,
                icon: Icon(
                  Icons.close,
                  color: UIColor.color_t3,
                ),
                onPressed: () {
                  _phoneTextController.text = "";
                  setState(() {});
                },
              )
            : null,
      ),
      onChanged: (text) {
        setState(() {});
      },
    );
  }

  Widget _renderPwd() {
    return TextField(
      controller: _pwdTextController,
      cursorColor: UIColor.color_primary,
      cursorHeight: 20.rpx,
      keyboardType: TextInputType.text,
      style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
      maxLength: 20,
      obscureText: true,
      decoration: InputDecoration(
        counterText: "",
        prefixIconConstraints:
            BoxConstraints(minWidth: 32.rpx, minHeight: 24.rpx),
        prefixIcon:
            SvgPicture.asset(R.image_login_lock, width: 24.rpx, height: 24.rpx),
        border: UnderlineInputBorder(
          borderSide: BorderSide(color: UIColor.color_divider, width: 1.rpx),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: UIColor.color_primary, width: 1.rpx),
        ),
        hintText: "请输入密码",
        hintStyle:
            TextStyle(color: Colors.black.withOpacity(0.26), fontSize: 16.rpx),
        suffixIcon: _pwdTextController.text.isNotEmpty
            ? IconButton(
                iconSize: 20.rpx,
                icon: Icon(
                  Icons.close,
                  color: UIColor.color_t3,
                ),
                onPressed: () {
                  _pwdTextController.text = "";
                  setState(() {});
                },
              )
            : null,
      ),
      onChanged: (text) {
        setState(() {});
      },
    );
  }

  _onClickGetCode() {
    if (_phoneTextController.text.isEmpty) {
      Tip.show("手机号不能为空");
      return;
    }
    var url = Api.HOST + "/v1/sms/send";
    var json = {};
    json["mobile"] = _phoneTextController.text;
    Api.submitx(context, url,
        data: json, successTip: "验证码已发送", failTip: "验证码获取失败", success: (data) {
      setState(() {
        _seconds = 0;
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          setState(() {
            if (_seconds < 60) {
              _seconds++;
            } else {
              _timer?.cancel();
              _timer = null;
            }
          });
        });
      });
    });
  }

  Widget _renderCode() {
    var _cancelWidget = _codeTextController.text.isNotEmpty
        ? IconButton(
            iconSize: 20.rpx,
            onPressed: () {
              _codeTextController.text = "";
              setState(() {});
            },
            icon: Icon(Icons.close, color: UIColor.color_t3))
        : 0.hspace;

    var isEnable = _phoneTextController.text.length == 11;
    var right = Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        _cancelWidget,
        _timer != null
            ? UText.get("${60 - _seconds}s", UIColor.color_info, 16.rpx)
            : GestureDetector(
                child: UText.get(
                    "发送验证码",
                    isEnable ? UIColor.color_primary : UIColor.color_t3,
                    16.rpx),
                onTap: isEnable ? _onClickGetCode : null,
              ),
      ],
    );

    return TextField(
      controller: _codeTextController,
      cursorColor: UIColor.color_primary,
      cursorHeight: 20.rpx,
      keyboardType: TextInputType.number,
      obscureText: false,
      maxLength: 6,
      style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
      decoration: InputDecoration(
        counterText: "",
        prefixIconConstraints:
            BoxConstraints(minWidth: 32.rpx, minHeight: 24.rpx),
        prefixIcon:
            SvgPicture.asset(R.image_login_lock, width: 24.rpx, height: 24.rpx),
        border: UnderlineInputBorder(
          borderSide: BorderSide(color: UIColor.color_divider, width: 1.rpx),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: UIColor.color_primary, width: 1.rpx),
        ),
        hintText: "请输入验证码",
        hintStyle:
            TextStyle(color: Colors.black.withOpacity(0.26), fontSize: 16.rpx),
        suffixIcon: right,
      ),
      onChanged: (text) {
        setState(() {});
      },
    );
  }

  Widget _renderTab() {
    return Row(
      children: [
        GestureDetector(
          onTap: () {
            if (_index != 0) {
              setState(() {
                _index = 0;
              });
            }
          },
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 4.rpx),
            child: UText.get(
                "密码登录",
                _index == 0 ? Colors.black : Colors.black.withOpacity(0.4),
                16.rpx),
          ),
        ),
        24.wspace,
        GestureDetector(
          onTap: () {
            if (_index != 1) {
              setState(() {
                _index = 1;
              });
            }
          },
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 4.rpx),
            child: UText.get(
                "验证码登录",
                _index == 1 ? Colors.black : Colors.black.withOpacity(0.4),
                16.rpx),
          ),
        ),
      ],
    );
  }
}
